package org.anddev.andengine.extension.svg;
/**
 * @author Eric Depta
 * @since 01:14:00 - 28.02.2011
 */
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.anddev.andengine.extension.svg.util.exception.SVGLoadException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;



public class SVGLoader {
	final SVGDoc mSVGDoc;
	
	public SVGLoader(final SVGDoc pSVGDoc) {
		this.mSVGDoc = pSVGDoc;
	}
	
	public void loadFromAsset(final String pAssetPath) throws SVGLoadException {
		
		try {
			this.load(this.mSVGDoc.mContext.getAssets().open(pAssetPath));
		} catch (final IOException e) {
			throw new SVGLoadException("Could not load SVG File from asset: " + pAssetPath, e);
		}
	}

	public void load(final InputStream pInputStream) throws SVGLoadException {
		try{
			final SAXParserFactory spf = SAXParserFactory.newInstance();
			//spf.setNamespaceAware(true);
			
			final SAXParser sp = spf.newSAXParser();
			final XMLReader xr = sp.getXMLReader();
			final SVGParser svgParser = new SVGParser(this.mSVGDoc);
			xr.setContentHandler(svgParser);
			xr.parse(new InputSource(new BufferedInputStream(pInputStream)));
		} catch (final SAXException e) {
			throw new SVGLoadException(e);
		}  catch (final ParserConfigurationException pe) {
		} catch (final IOException e) {
			throw new SVGLoadException(e);
		}
	}
}
